package org.net.cms.service.payment;

import jakarta.annotation.Resource;
import org.net.cms.controller.app.payment.vo.AppPaymentReqVO;
import org.net.cms.dao.PaymentDto;
import org.net.cms.mapper.ParentAccountMapper;
import org.net.cms.mapper.PaymentMapper;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PaymentServiceImpl implements PaymentService {
    @Resource
    private PaymentMapper paymentMapper;

    @Resource
    private ParentAccountMapper parentAccountMapper;

    @Override
    public PaymentDto getById(Integer id) {
        return paymentMapper.selectById(id);
    }

    @Override
    public List<PaymentDto> appGetAll() {
        Integer parentId = getParentId();
        return paymentMapper.selectAll(parentId);
    }

    @Override
    public List<PaymentDto> adminGetAll(int type) {
        return paymentMapper.selectAllByStatus(type);
    }

    public Integer getParentId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        String phone = userDetails.getUsername();
        return parentAccountMapper.getParentAccountByPhone(phone).getId();
    }

    @Override
    public void save(PaymentDto payment) {
        if (payment.getDeleted() == null) {
            payment.setDeleted(false);
        }
        paymentMapper.insert(payment);
    }

    @Override
    public void update(AppPaymentReqVO payment) {
        payment.setParentId(getParentId());
        paymentMapper.updateById(payment);
    }

    @Override
    public void delete(int studentId) {
        paymentMapper.deletePaymentByStudentId(studentId);
    }
}
